package com.wing.qualityTesting.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.Idempotent;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.enums.ProductEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.productionPlan.service.ProductionWorkOrderService;
import com.wing.qualityTesting.model.entity.QualityTestingRecord;
import com.wing.qualityTesting.model.entity.WorkOrderQualityTestingTask;
import com.wing.qualityTesting.model.request.WorkOrderQualityTestingTaskForm;
import com.wing.qualityTesting.model.response.QualityDetailRecordInfoVo;
import com.wing.qualityTesting.model.response.QualityTaskDetailRecordVo;
import com.wing.qualityTesting.model.response.WorkOrderQualityTestingTaskVO;
import com.wing.qualityTesting.service.QualityTestingRecordService;
import com.wing.qualityTesting.service.WorkOrderQualityTestingTaskService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.ant.Main;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

/**
 * 研发 - 质检任务
 *
 * @version 1.1.0
 * @Author hz
 * @Date 2024-10-28 14:24
 **/
@Slf4j
@Validated
@Api(value = "Admin-研发-质检任务", tags = "#/res/quality/workOrderQualityTask")
@RestController("resOrderQualityTaskController")
@RequestMapping("quality/admin/workOrderQualityTask")
@RequiredArgsConstructor
public class ResOrderQualityTaskController {

    @Autowired
    private WorkOrderQualityTestingTaskService workOrderQualityTestingTaskService;

    @Autowired
    private QualityTestingRecordService qualityTestingRecordService;

    @Autowired
    private ProductionWorkOrderService productionWorkOrderService;

    @ApiOperation(value = "查询研发质检任务表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "sort", value = "排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "order", value = "排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "processId", value = "工序id", dataType = "Long", paramType = "query")
            , @ApiImplicitParam(name = "workOrderCode", value = "工单编号", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "code", value = "质检任务编号", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "status", value = "状态:inspect(0,送检中);finish(1,完成)", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<WorkOrderQualityTestingTaskVO> list(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "asc") String order
            , Long processId
            , String workOrderCode
            , String code
            , WorkOrderQualityTestingTask.Status status
            ,String reportOrderCode
            ,String qualityTestingCategoryId
            ,String qcQualityTypeId
            ,String startCreateTime
            ,String endCreateTime
            ,String inspector
            ,String getName
            ,String workshopName
    ) {

        Page<WorkOrderQualityTestingTaskVO> pg = new Page<>(page, limit);
        Map<String,Object> paramMap = new HashMap();
        if (processId != null) {
            paramMap.put("processId", processId);
        }
        if (StringUtils.isNotBlank(workOrderCode)) {
            paramMap.put("workOrderCode", workOrderCode);
        }
        if (StringUtils.isNotBlank(code)) {
            paramMap.put("code", code);
        }
        if (status != null) {
            paramMap.put("status", status.getValue());
        }
        paramMap.put("enterpriseCode", JwtUtils.getEnterpriseCode());
        if(StringUtils.isNotBlank(reportOrderCode)){
            paramMap.put("reportOrderCode",reportOrderCode);
        }
        if(StringUtils.isNotBlank(qualityTestingCategoryId)){
            paramMap.put("qualityTestingCategoryId",qualityTestingCategoryId);
        }
        if(StringUtils.isNotBlank(qcQualityTypeId)){
            paramMap.put("qcQualityTypeId",qcQualityTypeId);
        }
        if(StringUtils.isNotBlank(startCreateTime)){
            paramMap.put("startCreateTime",startCreateTime);
        }
        if(StringUtils.isNotBlank(endCreateTime)){
            paramMap.put("endCreateTime",endCreateTime);
        }
        if(StringUtils.isNotBlank(inspector)){
            paramMap.put("inspector",inspector);
        }
        if(StringUtils.isNotBlank(getName)){
            paramMap.put("getName",getName);
        }
        if(StringUtils.isNotBlank(workshopName)){
            paramMap.put("workshopName",workshopName);
        }
        //搜索
        IPage<WorkOrderQualityTestingTaskVO> list = workOrderQualityTestingTaskService.pageList4app(pg, paramMap);
        for (WorkOrderQualityTestingTaskVO item : list.getRecords()) {
            if (item.getCreator().equals(JwtUtils.getLoginUserId())) {
                item.setWhetherEdit(0);
            }

            //查询质检性质
            String qualityAttributes = this.productionWorkOrderService.getQualityAttributes(item.getWorkOrderId());
            if (StrUtil.isNotBlank(qualityAttributes)) {
                item.setQualityAttributes(qualityAttributes);
            }

            //抽检数
            int cqs = workOrderQualityTestingTaskService.selectCJCount(item.getId());
            item.setDetectionQuantity(cqs);
            //合格数
            item.setQualifiedQuantity(item.getSubmissionQuantity() - item.getNotQuantity());
            if (item.getNotQuantity() > 0){
                BigDecimal numeratorBd = new BigDecimal(item.getSubmissionQuantity() - item.getNotQuantity());
                if (numeratorBd.compareTo(BigDecimal.ZERO) != 0) {
                    //合格率
                    BigDecimal denominatorBd = new BigDecimal(item.getSubmissionQuantity());
                    // 执行除法，保留两位小数，使用四舍五入
                    BigDecimal percentage = numeratorBd.divide(denominatorBd, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
                    // 设置保留两位小数
                    BigDecimal result = percentage.setScale(2, RoundingMode.HALF_UP);
                    item.setOkRate(result);
                }else {
                    item.setOkRate(BigDecimal.ZERO);
                }
            }else{
                item.setOkRate(new BigDecimal("100.00"));
            }
        }
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "添加开工单质检任务表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    @Idempotent(keyPrefix = "workOrderQualityTaskAdd")
    public JsonResult add(@Validated(WorkOrderQualityTestingTaskForm.Add.class) WorkOrderQualityTestingTaskForm workOrderQualityTestingTaskForm) {
        String status = "2";
        int add = workOrderQualityTestingTaskService.add(workOrderQualityTestingTaskForm, status);
        if ( add > 0) {
            if (add == 2) {
                return JsonResult.fail("添加失败 送检数不能大于剩余可送检数!");
            }
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }


    @ApiOperation(value = "修改开工单质检任务表", notes = "修改")
    @PutMapping("/update")
    @Idempotent(keyPrefix = "workOrderQualityTaskUpdate")
    public JsonResult update(@Validated(WorkOrderQualityTestingTaskForm.Update.class) WorkOrderQualityTestingTaskForm workOrderQualityTestingTaskForm) {
        WorkOrderQualityTestingTask workOrderQualityTestingTask = workOrderQualityTestingTaskService.getById(workOrderQualityTestingTaskForm.getId());
        Integer value = workOrderQualityTestingTask.getStatus().getValue();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(WorkOrderQualityTestingTask.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(workOrderQualityTestingTaskForm, workOrderQualityTestingTask, copyOptions);
        //关闭要判断是否有质检记录
        if (value != MaintenanceEnum.QualityStatus.DRL.getCode()) {
            //待认领 状态
            return JsonResult.fail("非待认领状态，不能关闭！");
        }
        //认领逻辑
        if ("inspect".equals(workOrderQualityTestingTask.getStatus().name())){
            int i = workOrderQualityTestingTaskService.updateInfoById(workOrderQualityTestingTask);
            if (i>0) {
                if (i == 2){
                    return JsonResult.fail("当前开工单无认领数 or 当前认领数大于开工单可认领数！");
                }
                return JsonResult.success("认领成功！");
            }
        }
        //其他逻辑
        else{
            if (workOrderQualityTestingTaskService.updateById(workOrderQualityTestingTask)) {
                return JsonResult.success("修改成功！");
            }
        }
        return JsonResult.fail("修改失败！");
    }

    /**
     * 根据质检记录详情 查询质检参数信息
     * @param taskId
     * @return
     */
    @ApiOperation(value = "查询任务详情", notes = "查询-任务明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", value = "质检任务id", required = true, dataType = "Long")
    })
    @GetMapping("/getTaskDetailRecord" )
    public JsonResult<QualityTaskDetailRecordVo> getTaskDetailRecord(Long taskId) {
        QualityTaskDetailRecordVo resultsData = qualityTestingRecordService.getTaskDetailRecord(taskId);
        return JsonResult.success(resultsData);
    }


    /**
     * 关闭质检任务
     *
     * @param id
     */
    @ApiOperation(value = "关闭质检任务", notes = "关闭-质检任务")
    @PutMapping("/close/{id}")
    public JsonResult close(@PathVariable("id") Long id) {
        int close = qualityTestingRecordService.close(id);
        if(close > 0){
            if (close == 2){
                return JsonResult.fail("该任务处于待认领状态 认领后才可关闭！");
            }
            return JsonResult.success("关闭成功");
        }else{
            return JsonResult.fail("关闭失败");
        }
    }




}
